package com.octopus.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONObject;
import com.octopus.conifg.WxConstantConfig;
import com.octopus.domain.AccessToken;
import com.octopus.domain.TemplateData;
import com.octopus.domain.TemplateMsgParam;
import com.octopus.service.SendTemplateMsgService;
import com.octopus.service.TokenService;
import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class SendTemplateMsgServiceImpl implements SendTemplateMsgService {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private WxConstantConfig wxConstantConfig;

    /** 模板消息推送 **/
    @Override
    public void sendWeChatTemplateMsg(List<String> openIdList, String templateId, TemplateMsgParam msgParam) {
        // 获取token
        AccessToken accessToken = tokenService.getAccessToken();
        // 接口地址
        String msgApiUrl = wxConstantConfig.getMsgApiUrl() + "?access_token=" + accessToken.getAccessToken();
        sendMsg(openIdList, templateId, msgApiUrl, msgParam);
    }

    /** 发送模版消息 **/
    private void sendMsg(List<String> openIdList, String templateId, String msgApiUrl,
            TemplateMsgParam msgParam) {
        // 整体参数map
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("template_id", templateId);
        paramMap.put("data", getDataMap(null));
        for (String openId : openIdList) {
            paramMap.put("touser", openId);
            log.info("开始微信公众号消息通知 param->{}", JSONObject.toJSONString(paramMap));
            String result = HttpUtil.post(msgApiUrl, JSONObject.toJSONString(paramMap));
            log.info("结束微信公众号消息通知 result->{}", result);
        }
    }

    /**
     * 消息主题显示相关map
     *
     * @return String
     */
    public Map<String, Object> getDataMap(String param) {
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("keyword1", new TemplateData(param, "#173177"));
        return dataMap;
    }

}
